// Modules to control application life and create native browser window
let Base64 = require('js-base64').Base64
const {
  app,
  BrowserWindow,
  BrowserView,
  Menu,
  session
} = require('electron');
const path = require('path');
const electron = require("electron");
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;


const isMac = process.platform === 'darwin'

const template = [
  // { role: 'fileMenu' }
  {
    label: '文件',
    submenu: [
      {
        role: 'quit',
        label: '退出'
      }
    ]
  },
  // { role: 'editMenu' }
  {
    label: '编辑',
    submenu: [{
        role: 'undo',
        label: '撤销'
      },
      {
        role: 'redo',
        label: '重做'
      },
      {
        type: 'separator'
      },
      {
        role: 'cut',
        label: '剪切'
      },
      {
        role: 'copy',
        label: '复制'
      },
      {
        role: 'paste',
        label: '粘贴'
      },
      {
        role: 'delete',
        label: '删除'
      },
      {
        type: 'separator'
      },
      {
        role: 'selectAll',
        label: '全选'
      }
    ]
  },
  // { role: 'viewMenu' }
  {
    label: '视图',
    submenu: [{
        role: 'reload',
        label: '刷新'
      },
      {
        role: 'forcereload',
        label: '强制刷新'
      },
      {
        role: 'toggledevtools',
        label: '打开开发者工具'
      },
      {
        type: 'separator'
      },
      {
        role: 'resetzoom',
        label: '重置缩放'
      },
      {
        role: 'zoomin',
        label: '放大'
      },
      {
        role: 'zoomout',
        label: '缩小'
      },
      {
        type: 'separator'
      },
      {
        role: 'togglefullscreen',
        label: '全屏'
      }
    ]
  },
  // { role: 'windowMenu' }
  {
    label: '窗口',
    submenu: [{
        role: 'minimize',
        label: '最小化'
      },
      {
        role: 'zoom',
        label: '最大化'
      },
      {
        role: 'close',
        label: '关闭'
      }
    ]
  },
  {
    role: 'help',
    label: '帮助',
    submenu: [{
      label: '关于作者',
      click: async () => {
        const {
          shell
        } = require('electron')
        // await shell.openExternal('https://electronjs.org')
      }
    }]
  }
]

const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)

function createWindow() {
  const {
    width,
    height
  } = electron.screen.getPrimaryDisplay().workAreaSize;
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: width,
    height: height,
    alwaysOnTop: true,
    frame: false,
    transparent: true,
    x: 0,
    y: 0,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true
    }
  });
  mainWindow.setIgnoreMouseEvents(true);
  // and load the index.html of the app.
  mainWindow.loadFile('index.html');

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })
}

function createBrowserWindow() {
  const width = 1920;
  const height = 1080;
  let win = new BrowserWindow({
    width: width,
    height: height,
    backgroundColor: '#5D9BCC'
  })
  win.on('closed', () => {
    win = null
  })
  win.on('resize', (e) => {
    console.log('调整窗口大小', e)
  })
  let view = new BrowserView()
  win.setBrowserView(view)
  view.setBackgroundColor('#000000')
  view.setBounds({
    x: 0,
    y: 0,
    width: width,
    height: height
  })
  view.webContents.loadURL('https://im.dingtalk.com')
  view.webContents.openDevTools()
  view.setAutoResize({
    width: true,
    height: true,
    horizontal: true,
    vertical: true
  })
  attachDevTools(view)
}

function attachDevTools (window) {
  let win = window

  try {
    win.webContents.debugger.attach('1.1')
  } catch (err) {
    console.log('Debugger attach failed : ', err)
  }

  win.webContents.debugger.on('detach', (event, reason) => {
    console.log('Debugger detached due to : ', reason)
  })

  win.webContents.debugger.on('message', (event, method, params) => {
    console.log('method', method.indexOf('webSocket') > -1)
    // if (method.indexOf('webSocket') > -1) {
    //   if (params['response']) {
    //     if (params['response']['payloadData']) {
    //       let obj = JSON.parse(params['response']['payloadData'])
    //       if (obj.body !== undefined) {
    //         console.log('body -------------> ', JSON.stringify(obj.body).slice(0, 200))
    //       } else {
    //         console.log('payloadData ----->', method, new Date().getTime(), JSON.stringify(obj).slice(0, 120))
    //       }
    //     } else {
    //       console.log('response ----->', method, new Date().getTime(), JSON.stringify(params['response']).slice(0, 120))
    //     }
    //   } else {

    //   }
    // }

    if (method.indexOf('webSocket') > -1) {
      if (params['response']) {
        if (params['response']['payloadData']) {
          let obj = JSON.parse(params['response']['payloadData'])
          if (obj.body !== undefined && obj.lwp !== undefined && obj.lwp === '/s/sync') {
            if (obj.body['1']) {
              if (obj.body['1']['6']) {
                if (obj.body['1']['6'][0]) {
                  if (obj.body['1']['6'][0]['2']) {
                    console.log('str -----> ', obj.body['1']['6'][0]['2'])
                    // console.log('解密后', Base64.decode(obj.body['1']['6'][0]['2']))
                  }
                }
              }
            }
          } else {
            console.log('payloadData ----->', method, new Date().getTime(), JSON.stringify(obj).slice(0, 120))
          }
        } else {
          console.log('response ----->', method, new Date().getTime(), JSON.stringify(params['response']).slice(0, 120))
        }
      } else {

      }
    }

  })

  win.webContents.debugger.sendCommand('Network.enable')

}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.name = '弹钉钉'

app.on('ready', createBrowserWindow);


// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') app.quit()
});

app.on('activate', function () {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) createWindow()
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.